<?php
namespace bee;
/**
 * @todo nije provjereno handle-aju li se podaci o stranici (možda formi ...) na kojoj je objekt snimljen
 * @author dzelenika
 *
 */

class factory
{
  public static function load($objectID, $page = "")
  {
    if(isset($_SESSION[$objectID][$page]))
    { //echo "\n<br />: $objectID " .strlen($_SESSION[$objectID][$page]["object"]);
      $serialized = $_SESSION[$objectID][$page]["object"];// preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $_SESSION[$objectID][$page]["object"] );
      //die( "\n<br />\nSR: $serialized<br />");
      //if($objectID =="frm201206080137") echo($serialized);
      //$retVal = $serialized;
      $retVal = unserialize($serialized);

      //if($objectID == "frm_201409082327")
      //if($objectID == "bee_plugin_class")
      //echo(print_r($retVal, true));
      //$retVal = unserialize(str_replace("~~NULL_BYTE~~", "\0", $serialized));
      //print_r($retVal);
      //die("===");
      if($retVal)////------------>
      { //file_put_contents("/home/damir/bee/logs/" . time(),  print_r($retVal, true));
        //echo( "\n<br />"  . print_r($retVal));

        return $retVal;
      } else
      { //echo "bee\\factory::load ObjectID: $objectID Page: $page# FATAL ERROR CALL DY";
        return false;
      }
    } else
    {
      //echo "bee\\factory::load Not se object $objectID / $page ";
      return false;
    }
  }

  public static function save($object, $objectID = "", $page = "")
  {
    //die("<br />:SAV: $objectID ");
    try
    {
      if(!$objectID)
      {
        $objectID = md5(session_id() . date("YmdHis") . rand(0, 99999999999));
      }
      //echo "<br />SAV: $objectID ";

      //$o = array("object" => serialize($object));
      //$p = array($page => $o);
      //$_SESSION[$objectID] = $p;

//       if($objectID == "ts_201511011613_")
//       {
        //echo("H E R E\n");
//         if(isset($_SESSION))
//         {
//           if(isset($_SESSION[$objectID]))
//           {
//            print_r($_SESSION[$objectID]);
//             echo "\n.....................................................";
//           }
//          echo "\n-----------------------------------------------------";
//          print_r($_SESSION);
//         }



        //$_SESSION[$objectID][$page]["object"] =
//        serialize($object);
//       } else
//       {
       $_SESSION[$objectID][$page]["object"] = serialize($object);
//       }
       //print_r($_SESSION[$objectID]);
    } catch (Exception $e)
    {
      echo "Dy";// . print_r($object, true);
    }
  	return $objectID;
  }

  public static function clear($objectID)
  { if(isset($_SESSION[$objectID]))
    { unset($_SESSION[$objectID]);
    }
  }

}


function serialize_fix_callback($match) {
  return 's:' . strlen($match[2]);
}




function mb_unserialize($serial_str) {
  $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
  return unserialize($out);
}

function unserializesession( $data )
{
  if(  strlen( $data) == 0)
  {
    return array();
  }

  // match all the session keys and offsets
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();

  $lastOffset = null;
  $currentKey = '';
  foreach ( $matchesarray[2] as $value )
  {
    $offset = $value[1];
    if(!is_null( $lastOffset))
    {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset );
      $returnArray[$currentKey] = unserialize($valueText);
    }
    $currentKey = $value[0];

    $lastOffset = $offset + strlen( $currentKey )+1;
  }

  $valueText = substr($data, $lastOffset );
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;
}





define('PS_DELIMITER', '|');
define('PS_UNDEF_MARKER', '!');

function session_real_decode($str)
{
  $str = (string)$str;

  $endptr = strlen($str);
  $p = 0;

  $serialized = '';
  $items = 0;
  $level = 0;

  while ($p < $endptr) {
    $q = $p;
    while ($str[$q] != PS_DELIMITER)
      if (++$q >= $endptr) break 2;

    if ($str[$p] == PS_UNDEF_MARKER) {
      $p++;
      $has_value = false;
    } else {
      $has_value = true;
    }

    $name = substr($str, $p, $q - $p);
    $q++;

    $serialized .= 's:' . strlen($name) . ':"' . $name . '";';

    if ($has_value) {
      for (;;) {
        $p = $q;
        switch ($str[$q]) {
          case 'N': /* null */
          case 'b': /* boolean */
          case 'i': /* integer */
          case 'd': /* decimal */
            do $q++;
            while ( ($q < $endptr) && ($str[$q] != ';') );
            $q++;
            $serialized .= substr($str, $p, $q - $p);
            if ($level == 0) break 2;
            break;
          case 'R': /* reference  */
            $q+= 2;
            for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
            $q++;
            $serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
            if ($level == 0) break 2;
            break;
            case 'r': /* reference  */
              $q+= 2;
              for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
              $q++;
              $serialized .= 'r:' . ($id + 1) . ';'; /* increment pointer because of outer array */
              if ($level == 0) break 2;
              break;
          case 's': /* string */
            $q+=2;
            for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
            $q+=2;
            $q+= (int)$length + 2;
            $serialized .= substr($str, $p, $q - $p);
            if ($level == 0) break 2;
            break;
          case 'a': /* array */
          case 'O': /* object */
            do $q++;
            while ( ($q < $endptr) && ($str[$q] != '{') );
            $q++;
            $level++;
            $serialized .= substr($str, $p, $q - $p);
            break;
          case '}': /* end of array|object */
            $q++;
            $serialized .= substr($str, $p, $q - $p);
            if (--$level == 0) break 2;
            break;
          default:
            return false;
        }
      }
    } else {
      $serialized .= 'N;';
      $q+= 2;
    }
    $items++;
    $p = $q;
  }
  return unserialize( 'a:' . $items . ':{' . $serialized . '}' );
}
